package org.scs.carleton.ca.pgdt.core.ui.editors;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.scs.carleton.ca.pgdt.core.ParseException;
import org.scs.carleton.ca.pgdt.core.internal.parser.TokenMgrError;

/**
 * Marker pool for the editor.  All marker creations should go through this.
 * 
 * @author tessierj
 *
 */
public final class EditorMarkerPool {
	private static EditorMarkerPool instance;
	
	private HashMap<IResource, IMarker> markerMap;
	
	private EditorMarkerPool() {
		markerMap = new HashMap<IResource, IMarker>(5);
	}
	
	public static synchronized EditorMarkerPool getInstance() {
		if (instance == null) {
			instance = new EditorMarkerPool();
		}
		return instance;
	}
	
	public void removeErrorMarker(IResource resource) {
		IMarker marker = markerMap.get(resource);
		
		if (marker != null) {
			try {
				//Delete the old marker
				marker.delete();
			}
			catch (CoreException ce) {
				//Could not delete the marker.  WHY ECLIPSE, WHY?!
			}
		}
	}
	
	public void createErrorMarker(IResource resource, ParseException e) {
		removeErrorMarker(resource);
		
		//Now create a new one
		try {
			IMarker marker = resource.createMarker(IMarker.PROBLEM);
			Map<String, Object> attributes = new HashMap<String, Object>(10);
			attributes.put(IMarker.LINE_NUMBER, Integer.valueOf(e.currentToken.endLine));
			attributes.put(IMarker.SEVERITY, Integer.valueOf(IMarker.SEVERITY_ERROR));
			attributes.put(IMarker.MESSAGE, e.getMessage());
			attributes.put(IMarker.TRANSIENT, Boolean.TRUE);
			marker.setAttributes(attributes);
			markerMap.put(resource, marker);
		}
		catch (CoreException ce) {
			//Could not create marker...
		}
	}
	
	public void createErrorMarker(IResource resource, TokenMgrError e) {
		removeErrorMarker(resource);
		
		//Now create a new one
		try {
			IMarker marker = resource.createMarker(IMarker.PROBLEM);
			Map<String, Object> attributes = new HashMap<String, Object>(10);
			attributes.put(IMarker.LINE_NUMBER, Integer.valueOf(e.getErrorLine()));
			attributes.put(IMarker.SEVERITY, Integer.valueOf(IMarker.SEVERITY_ERROR));
			attributes.put(IMarker.MESSAGE, e.getMessage());
			attributes.put(IMarker.TRANSIENT, Boolean.TRUE);
			marker.setAttributes(attributes);
			markerMap.put(resource, marker);
		}
		catch (CoreException ce) {
			//Could not create marker...
		}
	}
}
